﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace VietImage.Models
{
    public partial class NoticeEmail
    {
        #region Properties
        public Email EmailKind
        {
            get
            {
                return this.GetEmailKind();
            }
        }

        public Status Status
        {
            get
            {
                return this.GetStatus();
            }
        }
        #endregion

        #region Methods

        public List<ErrorItem> SendEmail(int id_User, int id_Lang)
        {
            Email e = this.GetEmailKind();

            System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();

            message.To.Add(this.ReceivedEmail);
            message.Subject = e.Title;
            message.From = new System.Net.Mail.MailAddress("admin@vietimage.com", "VietImage Administrator");

            string body = e.Tenor;
            message.Body = body;
            System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("smtp.gmail.com");
            smtp.Port = 25;
            smtp.Credentials = new System.Net.NetworkCredential("admin@vietimage.com", "123456");
            message.IsBodyHtml = true;
            smtp.EnableSsl = true;
            smtp.Send(message);

            return e.SendEmail(id_User, id_Lang);
        }

        public Email GetEmailKind()
        {
            VietImageDataClassesDataContext _db = new VietImageDataClassesDataContext();
            var v = _db.Emails.Where(p => p.ID_Email == this.ID_Email);
            if (v.Count() == 0)
                return null;
            return v.First();
        }

        public Status GetStatus()
        {
            VietImageDataClassesDataContext _db = new VietImageDataClassesDataContext();
            var v = _db.Status.Where(p => p.ID == this.ID_Status);
            if (v.Count() == 0)
                return null;
            return v.First();
        }
        #endregion

        #region Static Methods
        public static NoticeEmail Parse(System.Object value)
        {
            NoticeEmail temp = null;
            try
            {
                temp = (NoticeEmail)value;
            }
            catch (Exception ex)
            {
            }
            return temp;
        }

        public static NoticeEmail GetNoticeEmail(String receivedEmail, int id_Email)
        {
            VietImageDataClassesDataContext _db = new VietImageDataClassesDataContext();
            var v = _db.NoticeEmails.Where(p => p.ReceivedEmail == receivedEmail && p.ID_Email == id_Email);
            if (v.Count() == 0)
                return null;
            return v.First();
        }

        public static List<NoticeEmail> GetListSubscriberEmail()
        {
            VietImageDataClassesDataContext _db = new VietImageDataClassesDataContext();
            var v = from ne in _db.NoticeEmails
                        join sc in _db.Subscribers on ne.ReceivedEmail equals sc.Email
                        select ne;

            if (v.Count() == 0)
                return null;
            return v.OrderByDescending(p=>p.ID).ToList();
        }

        public static List<NoticeEmail> GetListUserEmail()
        {
            VietImageDataClassesDataContext _db = new VietImageDataClassesDataContext();
            var v = from ne in _db.NoticeEmails
                       join u in _db.Users on ne.ReceivedEmail equals u.Email
                       select ne;

            if (v.Count() == 0)
                return null;
            return v.OrderByDescending(p=>p.ID).ToList();
        }

        public static List<NoticeEmail> GetListSentEmail()
        {
            VietImageDataClassesDataContext _db = new VietImageDataClassesDataContext();
            var v = _db.NoticeEmails.Where(p => p.ID_Status == 17);
            if (v.Count() == 0)
                return null;
            return v.ToList();
        }

        public static List<NoticeEmail> GetList()
        {
            VietImageDataClassesDataContext _db = new VietImageDataClassesDataContext();
            var v = _db.NoticeEmails.OrderByDescending(p => p.ID);
            if (v.Count() == 0)
                return null;
            return v.ToList();
        }

        public static List<NoticeEmail> GetListAvailable()
        {
            VietImageDataClassesDataContext _db = new VietImageDataClassesDataContext();
            var v = _db.NoticeEmails.Where(p => p.ID_Status != 2);
            if (v.Count() == 0)
                return null;
            return v.ToList();
        }

        public static List<NoticeEmail> GetListNotAvailable()
        {
            VietImageDataClassesDataContext _db = new VietImageDataClassesDataContext();
            var v = _db.NoticeEmails.Where(p => p.ID_Status == 2);
            if (v.Count() == 0)
                return null;
            return v.ToList();
        }

        private static List<ErrorItem> InputInfomationValidation(NoticeEmail noticeEmail)
        {
            List<ErrorItem> errorList = new List<ErrorItem>();
            if (noticeEmail.ReceivedEmail == "")
                errorList.Add(new ErrorItem("ReceivedEmail", "Received Email is required"));
            if (noticeEmail.ReceivedEmail.Length > 50)
                errorList.Add(new ErrorItem("ReceivedEmail", "ReceivedEmail is only allow up to 50 characters."));
            if (noticeEmail.ID_Email < 1)
                errorList.Add(new ErrorItem("ID_Email", "Email kind is required"));
            if (noticeEmail.ID_Status < 1)
                errorList.Add(new ErrorItem("ID_Status", "ID_Status is required"));
            return errorList;
        }

        public static List<ErrorItem> Insert(ref NoticeEmail ii, int id_User, int id_Lang)
        {
            VietImageDataClassesDataContext _db = new VietImageDataClassesDataContext();
            List<ErrorItem> errorList = InputInfomationValidation(ii);
            if (errorList.Count == 0)
            {
                Nullable<Int32> id = null;
                int errorMess = _db.AddNoticedEmail(id_User, ref id, ii.ReceivedEmail, ii.ID_Email);
                if (errorMess == 1)
                    ii.ID = id.Value;
                
                if(errorMess != 1) errorList.Add(new ErrorItem("ErrorMessage", _db.ErrorMessages.Single(p => p.ID_ErrorMessage == errorMess && p.ID_Language == id_Lang).Description));
            }
            return errorList;
        }

        public static List<ErrorItem> ChangeInformation(NoticeEmail ic, int id_User, int id_Lang)
        {
            VietImageDataClassesDataContext _db = new VietImageDataClassesDataContext();
            List<ErrorItem> errorList = InputInfomationValidation(ic);
            if (errorList.Count == 0)
            {
                NoticeEmail oi = _db.NoticeEmails.Single(p => p.ID == ic.ID);
                String content = "";
                content = oi.ReceivedEmail + "_" + oi.ID_Status + "_" + oi.ID_Email;
                int errorMess = _db.ChangeNoticeEmail(id_User, ic.ID, ic.ReceivedEmail, ic.ID_Status, content, 0, 0);
                
                    if(errorMess != 1) errorList.Add(new ErrorItem("ErrorMessage", _db.ErrorMessages.Single(p => p.ID_ErrorMessage == errorMess && p.ID_Language == id_Lang).Description));
            }
            return errorList;
        }

        public static List<ErrorItem> ChangeInformation(NoticeEmail ic, int id_User, int id_Log, int id_Lang)
        {
            VietImageDataClassesDataContext _db = new VietImageDataClassesDataContext();
            List<ErrorItem> errorList = InputInfomationValidation(ic);
            if (errorList.Count == 0)
            {
                NoticeEmail oi = _db.NoticeEmails.Single(p => p.ID == ic.ID);
                int errorMess = _db.ChangeNoticeEmail(id_User, ic.ID, ic.ReceivedEmail, ic.ID_Status, "", id_Log, 1);
                
                    if(errorMess != 1) errorList.Add(new ErrorItem("ErrorMessage", _db.ErrorMessages.Single(p => p.ID_ErrorMessage == errorMess && p.ID_Language == id_Lang).Description));
            }
            return errorList;
        }
        #endregion

        #region Search

        private static String BuildQuery(Dictionary<String, System.Object> parametersList, Dictionary<String, bool> exactList)
        {
            String query = "";

            DateTime noValue = new DateTime(2000, 1, 1);

            foreach (KeyValuePair<String, System.Object> kvp in parametersList)
            {
                if (kvp.Key == "ID_Email" || kvp.Key == "ID_Status" || kvp.Key == "ID")
                {
                    if (int.Parse(kvp.Value.ToString()) >= 1)
                        query += kvp.Key + " = " + int.Parse(kvp.Value.ToString());
                }
                else if (kvp.Key == "CreatedTime")
                {
                    if (DateTime.Parse(kvp.Value.ToString()) != noValue)
                        query += "CreatedTime" + " = " + DateTime.Parse(kvp.Value.ToString()).ToString("yyyy-MM-dd") + "";
                }
            }

            if (parametersList.ContainsKey("CreatedbeginDate") && parametersList.ContainsKey("CreatedendDate"))
            {
                query += " DATEDIFF(day, " + DateTime.Parse(parametersList["CreatedendDate"].ToString()).ToString("yyyy-MM-dd") + " , CreatedTime) >= 0";
                query += " DATEDIFF(day, CreatedTime , " + DateTime.Parse(parametersList["CreatedbeginDate"].ToString()).ToString("yyyy-MM-dd") + ") >= 0";
            }

            return query;
        }

        public static System.Object GetNoticeEmail(Dictionary<String, System.Object> parametersList, Dictionary<String, bool> exactList, bool oneRow)
        {
            VietImageDataClassesDataContext _db = new VietImageDataClassesDataContext();
            String query = BuildQuery(parametersList, exactList);
            var v = _db.ExecuteQuery<NoticeEmail>(query);
            if (oneRow)
            {
                if (v.Count() == 0)
                    return null;
                return v.First();
            }
            if (v.Count() == 0)
                return null;
            return v.ToList();
        }

        #endregion
    }
}